package layui.controller.product;

import com.google.gson.Gson;
import layui.dao.ProductDao;
import layui.dao.impl.ProductDaoImpl;
import layui.entity.Product;
import layui.vo.ResponseData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * @Author lzp
 * @Date 2023-11-16
 */
@WebServlet("/admin/product/product_list")
public class FindAllProductServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        ProductDao productDao =new ProductDaoImpl();
        List<Product> list =productDao.selectAll();
         /*
            把后台（服务器）的数据响应到前端页面，有以下两个方法：
            方法一（同步）：把数据设置在某个作用域对象 -> 页面跳转到 JSP 页面 -> JSTL + EL
            方法二（异步）：把数据封装到统一的响应对象 ->
            把数据转换为 JSON 字符串 ->
            通过 PrintWriter 对象，把 JSON 字符串输出到页面中 ->
            把 JSON 字符串转换为 JavaScript 对象 -> DOM操作
         */

        ResponseData responseData = new ResponseData();
        responseData.setCode(200);
        responseData.setMsg("success");
        responseData.setData(list);

        String json = new Gson().toJson(responseData);
        PrintWriter out = resp.getWriter();
        out.println(json);
        out.flush();
        out.close();

    }
}
